let ws = new WebSocket('ws://30.225.3.90:8888');

ws.onopen = function (event) {
    console.log('连接成功');
    var name = prompt('请输入用户名:');

    ws.send(JSON.stringify({
        type: 'login',
        name: name
    }));

    if (!name) {
        alert('好你个坏蛋，竟然没有输入用户名');
    }
};

ws.onmessage = function (event) {
    let data = JSON.parse(event.data);
    console.log(data);

    switch (data.type) {
        case 'close':
        case 'login':
            $("#user-box").html('');

            data.users.forEach(function (item) {
                $("#user-box").append(`<p style="color: grey;">${item}</p>`);
            });

            if (data.msg) {
                $("#msg-box").append(`<p style="color: grey;">${data.msg}</p>`);
            }

            $("#msg-box").scrollTop(9999);

            break;
        case 'message':
            $("#msg-box").append(`<p><span style="color: #0A89FF">${data.time}</span> <span style="color: red">${data.name}:</span> ${data.msg}</p>`);
            $("#msg-box").scrollTop(9999);
            
            break;
    }
};

ws.onclose = function (event) {
    alert('连接关闭');
};

document.onkeydown = function (event) {
    if (event.keyCode == 13) {
        send();
    }
};

$("#send").click(function () {
    send();
});

function send() {
    let content = $("#content").val();
    $("#content").val(null);

    if (!content) {
        return;
    }

    ws.send(JSON.stringify({
        type: 'message',
        msg: content
    }));
};
